package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.mapper.StrategyMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ICommentService;
import cn.wolfcode.trip.base.service.IStrategyService;
import cn.wolfcode.trip.base.service.IUserCollectService;
import cn.wolfcode.trip.base.service.IUserGoodService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private StrategyMapper strategyMapper;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private IUserGoodService userGoodService;
    @Autowired
    private IUserCollectService userCollectService;

    public void saveOrUpdate(Strategy entity) {
        if (entity.getId() == null) {
            // 获取所属的评论id
            Long commentId = commentService.autoCommentId();
            entity.setCommentId(commentId);
            // 获取游记所属的点赞id
            Long goodId = userGoodService.autoUserGoodId();
            entity.setGoodId(goodId);

            // 获取所属的收藏id
            Long collectId = userCollectService.autoUserCollectId();
            entity.setCollectId(collectId);

            // 增加
            strategyMapper.insert(entity);
        } else {
            // 修改
            strategyMapper.updateByPrimaryKey(entity);
        }
    }

    public PageInfo<Strategy> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Strategy> list = strategyMapper.selectForList(qo);
        for (Strategy strategy : list) {
            // // 查询当前对象的点赞次数
            // int count = userGoodService.getCount(strategy.getGoodId());
            // strategy.setGoods(count);
            // 查询当前对象的收藏次数
            int count = userCollectService.getCount(strategy.getCollectId());
            strategy.setCollects(count);
        }
        return new PageInfo<>(list);

    }

    public List<Strategy> list() {
        return strategyMapper.selectEnable();
    }

    public Strategy get(Long id) {
        return strategyMapper.selectByPrimaryKey(id);
    }
}
